<template>
  <div class="relative">
    <div class="w-100vw">
      <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white" loop>
        <van-swipe-item v-for="(item, index) in bannerList" :key="index">
          <el-image :src="item" :fit="'contain'" />
        </van-swipe-item>
      </van-swipe>
    </div>
    <div class="w-full min-h-50vh bg-[#eee] p-10px">
      <div class="rounded-5px p-10px bg-white mb-10px">
        <div class="w-full flex items-end">
          <span class="font-bold">
            <span class="text-0.75rem text-price_red">￥</span>
            <span class="text-1.25em text-price_red">
              {{ padZeroPrice(price.minPrice) }}
              <span
                class="text-0.75rem text-price_red"
                v-if="price.maxPrice && price.maxPrice !== price.minPrice"
                >{{ '起' }}</span
              >
            </span>
            <!-- <span class="text-0.75rem line-through ml-1rem">￥6999.00</span> -->
          </span>
        </div>
        <div class="flex justify-between mt-0.75rem text-0.75rem">
          <div class="flex text-price_red">
            <div class="p-3px border mr-0.5rem bg-pink border-price_red" v-if="price.minBatch">
              {{ price.minBatch + '件起批' }}
            </div>
            <div class="p-3px border mr-0.5rem bg-pink border-price_red" v-if="price.minShipping">
              {{ price.minBatch + '件起发' }}
            </div>
            <div class="p-3px border mr-0.5rem bg-pink border-price_red">
              {{ goodsData?.spu?.isMixedBatch === 2 ? '支持混批' : '不支持混批' }}
            </div>
          </div>
          <!-- <div class="flex items-center">
          优惠
          <van-icon name="arrow" />
        </div> -->
        </div>
      </div>

      <div class="rounded-5px px-10px py-1rem bg-white mb-10px">
        <div>
          <span class="font-bold"> {{ goodsData?.spu?.goodsName }} </span>
        </div>
        <!-- <div class="text-0.75rem mt-1rem">144Hz高刷全面屏，华为笔记，专业PC级WPS</div> -->
      </div>

      <div class="rounded-5px px-10px pt-1rem py-0.5rem bg-white mb-10px">
        <Menu :title="'已选'" @click="buyingShow = true">
          <template #content>
            <span v-show="targetSpec.length === 0">{{ '选择规格' }}</span>
            <span
              class="mr-0.25rem"
              v-for="item in targetSpec"
              :key="item.optionId"
              v-show="targetSpec.length > 0"
              >{{ item.optionName }}</span
            >
          </template>
        </Menu>
        <Menu :title="'送至'" @click="selectAddress">
          <template #content>
            <div class="flex flex-col">
              <div class="w-full one-row-ellipsis max-w-70vw">
                {{ addressData.receiverAddress }}
              </div>
              <span class="mt-0.5rem">现货</span>
            </div>
          </template>
        </Menu>
        <Menu :showBorderBottom="false">
          <template #content>
            <div class="flex items-center">
              <van-icon name="passed" />
              <span class="ml-1rem text-0.75rem mr-0.75rem ml-0.5rem">满48元包邮</span>
              <van-icon name="passed" />
              <span class="ml-1rem text-0.75rem mr-0.75rem ml-0.5rem">发货开票</span>
              <van-icon name="passed" />
              <span class="ml-1rem text-0.75rem mr-0.75rem ml-0.5rem">售后保障</span>
            </div>
          </template>
        </Menu>
      </div>

      <div class="rounded-5px px-10px pt-1rem py-0.5rem bg-white mb-10px">
        <div class="flex justify-between items-center">
          <p class="font-bold">用户评价(1万+)</p>
          <span class="text-0.75rem">查看更多评价<van-icon name="arrow" /></span>
        </div>
        <div class="w-full">
          <span class="text-0.8rem">好评<span class="text-price_red">99%</span></span>
        </div>

        <div class="w-full my-0.8rem flex flex-wrap">
          <div
            class="h-2em px-0.8rem flex items-center mr-1rem text-0.75rem rounded-1rem"
            :class="commentLevel === '1' ? 'bg-primary text-white' : ' bg-[#ddd]'"
            @click="getGoodsList('1')"
          >
            好评
          </div>
          <div
            class="h-2em px-0.8rem flex items-center mr-1rem text-0.75rem rounded-1rem"
            :class="commentLevel === '2' ? 'bg-primary text-white' : ' bg-[#ddd]'"
            @click="getGoodsList('2')"
          >
            中评
          </div>
          <div
            class="h-2em px-0.8rem flex items-center mr-1rem text-0.75rem rounded-1rem"
            :class="commentLevel === '3' ? 'bg-primary text-white' : ' bg-[#ddd]'"
            @click="getGoodsList('3')"
          >
            差评
          </div>
        </div>

        <div v-for="item in commentList" :key="item.id">
          <div class="w-full my-1rem flex items-center">
            <van-image
              width="4rem"
              height="4rem"
              :src="item.image"
              fit="cover"
              round
              v-if="item.image"
            />
            <van-icon
              name="https://fastly.jsdelivr.net/npm/@vant/assets/icon-demo.png"
              size="4rem"
              v-else
            />
            <div class="ml-1rem flex flex-col">
              <span class="font-bold mb-0.5rem">{{ item.name }}</span>
              <van-rate v-model="item.star" icon="like" void-icon="like-o" size="16" />
            </div>
          </div>

          <p class="text-0.75rem mt-1rem">{{ item.content }}</p>
          <div class="mt-1rem grid grid-cols-4 gap-0.5rem">
            <van-image
              :src="node"
              fit="cover"
              round
              radius="1rem"
              class="aspect-ratio-1/1"
              v-for="(node, nodeIndex) in item.images.split(',')"
              :key="nodeIndex"
            />
          </div>
        </div>
      </div>
      <div v-show="paraList && paraList.length > 0">
        <div class="my-1rem font-bold">参数信息</div>
        <div class="rounded-5px px-10px pt-1rem py-0.5rem bg-white mb-10px">
          <div class="flex flex-col mb-1rem" v-for="(item, index) in paraList" :key="index">
            <span class="font-bold mb-0.5rem">{{ item.text }}</span>
            <span class="text-0.8rem text-[#aaa]">{{ item.value }}</span>
          </div>
        </div>
      </div>
      <div class="rounded-5px px-10px pt-1rem py-0.5rem bg-white mb-10px py-1.5rem">
        <div class="text-1.25em font-bold">产品描述</div>
        <div class="goods-desc py-20px" v-html="goodsData?.spuDesc?.htmlIntroduction"></div>
      </div>
      <div
        class="rounded-5px px-10px pt-1rem py-0.5rem bg-white mb-10px py-1.5rem"
        v-show="pdfFile?.url"
      >
        <div class="text-1.25em font-bold">产品文件预览</div>
        <div class="flex mt-1rem items-center" @click="downloadFile">
          <van-image width="2rem" height="2rem" :src="pdfImg" fit="cover" />
          <span class="ml-1rem font-bold">{{ pdfFile?.name }}</span>
        </div>
      </div>
      <!-- <div class="rounded-5px px-10px pt-1rem py-0.5rem bg-white mb-10px py-1.5rem">
      <div class="text-1.25em font-bold">免责声明</div>
    </div>
    <div class="rounded-5px px-10px pt-1rem py-0.5rem bg-white mb-10px py-1.5rem">
      <div class="text-1.25em font-bold">特别提醒</div>
    </div> -->
    </div>
    <div class="w-100vw bg-white flex py-10px pr-1rem sticky bottom-0 left-0">
      <div class="flex flex-1 mr-1rem justify-center">
        <div class="flex flex-col flex-center">
          <van-icon name="shopping-cart-o" class="text-1.5rem" />
          <span class="text-0.75rem mt-0.5rem">加入购物车</span>
        </div>
      </div>
      <van-button type="danger" round class="w-70vw" @click="buyingShow = true">
        立即购买
      </van-button>
    </div>
  </div>
  <van-action-sheet v-model:show="buyingShow" title="选择规格" closeable>
    <!-- <template #cancel> x </template> -->
    <div class="px-1rem pb-5rem flex flex-col max-h-50vh overflow-y-scroll">
      <div class="flex">
        <div class="w-5rem h-5rem bg-[#eee]">
          <van-image
            width="5rem"
            height="5rem"
            fit="contain"
            :src="goodsData?.spuDesc?.mainImages"
          />
        </div>
        <div class="ml-1rem flex flex-col">
          <div class="flex flex-col">
            <!-- <span class="font-bold text-price_red text-1.25rem">
              <span class="text-0.75rem">￥</span>179
            </span> -->
            <span v-if="countingPrice" class="text-1.25em text-price_red">
              {{ '正在估价...' }}
            </span>
            <span class="text-1.25em text-price_red" v-else-if="!priceObj?.payMoney">
              ￥
              {{ padZeroPrice(price.minPrice) }}
              <span
                class="text-0.75rem text-price_red"
                v-if="price.maxPrice && price.maxPrice !== price.minPrice"
                >{{ '起' }}</span
              >
            </span>
            <span v-else class="text-1.25em text-price_red">
              ￥
              {{ priceObj?.payMoney }}
            </span>
            <span class="font-bold text-0.75rem my-0.5rem"> {{ goodsData?.spu?.goodsName }} </span>
            <span class="text-0.75rem" v-show="targetSpec.length === specList.length"
              >已选：
              <span>
                <span v-for="item in targetSpec" :key="item.optionId">
                  {{ item.optionName + ' ' }}
                </span>
              </span>
              × {{ ' ' + goodsNum }}</span
            >
          </div>
        </div>
      </div>
      <div class="w-full flex flex-col" v-for="item in specList" :key="item.attributeId">
        <span class="font-bold">{{ item.attributeName }}</span>
        <div class="flex flex-wrap mt-0.5rem mb-1rem">
          <div
            class="text-0.75rem p-0.5rem bg-[#eee] mr-1rem rounded-0.5rem"
            v-for="node in item.attributeValue"
            :key="node.optionId"
            @click="selectSpec(item.attributeId, node.optionId, node.optionName)"
            :class="
              targetSpec.find((specItem) => item.attributeId === specItem.attributeId)?.optionId ===
              node.optionId
                ? '!bg-primary !text-white'
                : ''
            "
          >
            {{ node.optionName }}
          </div>
        </div>
      </div>
      <div class="flex justify-between">
        <span class="font-bold">数量</span>
        <van-stepper
          v-model="goodsNum"
          theme="round"
          button-size="22"
          disable-input
          @change="countPriceData"
        />
      </div>
    </div>

    <van-sticky :offset-bottom="0" position="bottom">
      <div class="flex justify-center w-100vw py-10px">
        <van-button
          type="danger"
          round
          class="w-90vw"
          @click="buying"
          :disabled="targetSpec.length !== specList.length"
        >
          {{ targetSpec.length === specList.length ? '立即购买' : '请选择规格' }}
        </van-button>
      </div>
    </van-sticky>
  </van-action-sheet>
</template>

<script setup>
import { ref, onActivated, inject } from 'vue'
import Menu from './components/menu.vue'
import { getGoods, getGoodsScore, getGoodsComment, getGoodsPrice, addGoodsOrder } from '@/api/goods'
import { useRoute, useRouter } from 'vue-router'
import { findMarketPriceRange, padZeroPrice } from '@/utils/price'
import { showUseAddressBox } from '@/utils/showApi'
import { GetOrderAddressDefault } from '@/api/member'
import { isLogin } from '@/utils/index'
import pdfImg from '@/assets/image/pdf.png'
import Cookies from 'js-cookie'

const route = useRoute()
const router = useRouter()
const rateNum = ref(3)
const goodsData = ref({})
const specList = ref([])
const bannerList = ref([])
const price = ref({})
const buyingShow = ref(false)
const goodsNum = ref(1)
const targetSpec = ref([])
const commentLevel = ref(null)
const commentList = ref([])
const paraList = ref([])
const pdfFile = ref({})
const priceObj = ref({})
const countingPrice = ref(false)
const backToTop = inject('toTop')
const addressData = ref({})
const targetAddressId = ref()
const commentCount = ref({
  allCount: 0,
  repeatCount: 0,
  imageVideoCount: 0,
  levelCount1: 0,
  levelCount2: 0,
  levelCount3: 0,
  star1: 0,
  star2: 0,
  star3: 0,
  star4: 0,
  star5: 0,
})

const init = () => {
  getGoods(route.query.id).then((res) => {
    if (res.code === 20000) {
      goodsData.value = res.data
      if (res.data.spuDesc.paraItems) {
        specList.value = res.data.specList
      }
      if (res.data.spuDesc.paraItems) {
        paraList.value = JSON.parse(res.data.spuDesc.paraItems)
      }
      if (res.data.spuDesc.video) {
        bannerList.value = [res.data.spuDesc.video]
      }
      bannerList.value.push(...res.data.imageList)
      price.value = findMarketPriceRange(res.data.skuList, 1)
      price.value.minBatch = findMinAlertNum(res.data.skuList).batchNum || 1
      price.value.minShipping = findMinAlertNum(res.data.skuList).batchNum || 1
      goodsData.value.skuList = res.data.skuList.map((item) => {
        item.spec = JSON.parse(item.spec)
        return item
      })
      pdfFile.value = res.data.spuDesc.pdfFile ? JSON.parse(res.data.spuDesc.pdfFile) : {}
    }
  })
  getGoodsScore(route.query.id).then((res) => {
    if (res.code === 20000) {
      commentCount.value = res.data
    }
  })
  getGoodsList('1')
  getDefaultAddress()
  backToTop()
}

// 获取评论列表
const getGoodsList = (level) => {
  commentLevel.value = level
  getGoodsComment({
    level,
    current: 1,
    size: 1,
    spuId: route.query.id,
  }).then((res) => {
    if (res.code === 20000) {
      commentList.value = res.data.records
    }
  })
}

const getDefaultAddress = () => {
  if (Cookies.get('token')) {
    GetOrderAddressDefault().then((res) => {
      if (res.code === 20000 && res.data) {
        targetAddressId.value = res.data.id
        addressData.value = {
          countryCode: res.data.countryId,
          provinceCode: res.data.provinceId,
          cityCode: res.data.cityId,
          receiverAddress: res.data.address,
          receiverContact: res.data.contact,
          receiverMobile: res.data.phone,
        }
      }
    })
  }
}

// 下载pdf
const downloadFile = () => {
  window.open(pdfFile.value.url)
}

// 获取最小起批量
const findMinAlertNum = (arr) => {
  if (arr) {
    return arr.reduce((min, current) => (current.alertNum < min.alertNum ? current : min))
  }
}

// 立即购买
const buying = () => {
  addGoodsOrder({
    ...addressData.value,
    companyParams: countPriceData(),
    payType: null,
    sourceType: 1,
  }).then((res) => {
    if (res.code === 20000) {
      buyingShow.value = false
      backToTop()
      router.push(`/order?id=${res.data.outTradeNo}`)
    }
  })
  //
}

const selectAddress = () => {
  isLogin(
    () => {
      showUseAddressBox(targetAddressId.value, (addressObj) => {
        targetAddressId.value = addressObj.id
        addressData.value = {
          countryCode: addressObj.countryId,
          provinceCode: addressObj.provinceId,
          cityCode: addressObj.cityId,
          receiverAddress: addressObj.address,
          receiverContact: addressObj.contact,
          receiverMobile: addressObj.phone,
        }
      })
    },
    () => {
      router.push('/login')
    },
  )
}

// 寻找对应的sku对象
const findSku = () => {
  const obj = goodsData.value.skuList.filter((sku) => {
    return targetSpec.value.every((specItem) => {
      return sku.spec.some((item) => {
        return item.valueId === specItem.optionId
      })
    })
  })
  return obj
}

const countPriceData = () => {
  if (targetSpec.value.length === specList.value.length) {
    const arr = findSku()
    if (arr && arr.length > 0) {
      const skuId = arr[0]?.goodsChannelSkuPriceList?.find((item) => item.type === 1)?.skuId
      const result = [
        {
          spuParams: [
            {
              skuParams: [
                {
                  skuId,
                  num: goodsNum.value,
                },
              ],
              spuId: arr[0]?.spuId,
            },
          ],
          companyId: goodsData.value.spu.companyId,
          type: 1,
        },
      ]
      countPrice(result)
      return result
    }
    return []
  }
  return []
}

// 计算价格
const countPrice = (arr) => {
  countingPrice.value = true
  const data = {
    ...addressData.value,
    companyParams: arr,
  }
  getGoodsPrice(data)
    .then((res) => {
      if (res.code == 20000) {
        priceObj.value = res.data
      }
    })
    .finally(() => {
      countingPrice.value = false
    })
}

// 选择规格
const selectSpec = (attributeId, optionId, optionName) => {
  const index = targetSpec.value.findIndex((item) => item.attributeId === attributeId)
  if (index > -1) {
    targetSpec.value[index].optionId = optionId
    targetSpec.value[index].optionName = optionName
  } else {
    targetSpec.value.push({
      attributeId,
      optionId,
      optionName,
    })
    targetSpec.value = formatTargetSpec()
  }
  countPriceData()
}

const formatTargetSpec = () => {
  const arr = []
  specList.value.forEach((item) => {
    const obj = targetSpec.value.find((node) => node.attributeId === item.attributeId)
    if (obj) {
      arr.push(obj)
    }
  })
  return arr
}

init()

onActivated(() => {
  init()
})
</script>

<style lang="scss" scoped>
.my-swipe .van-swipe-item {
  width: 100%;
  color: #fff;
  font-size: 20px;
  // line-height: 300px;
  text-align: center;
  // background-color: #39a9ed;
}
</style>
